import { useModel } from 'umi';
import React, { useLayoutEffect, useEffect, useState } from 'react';
import { Row, Col, Tree, Card, Checkbox, message, Button } from 'antd';
import ProForm, { ModalForm, ProFormText, ProFormSelect } from '@ant-design/pro-form';
import {
  actionclasslist,
  actionlist,
  getOrgTre,
  editRoleMenu,
} from '../service';
const EditMentModalForm = (props) => {
  const { initialState } = useModel('@@initialState');
  const [currentMenu, SetCurrentMenu] = useState(undefined);
  const [treeData, SetTreeData] = useState([]);

  const [actionClassData, SetActionClassData] = useState([]);
  const [actionData, SetActionData] = useState([]);
  //多选按钮样式
  const [indeterminate, setIndeterminate] = React.useState(false);
  const [checkAll, setCheckAll] = React.useState(false);
  const [checkedList, setCheckedList] = React.useState([]);
  const [actionClassList, setActionClassList] = React.useState([]);
  const [checkedTreeKeys, setCheckedTreeKeys] = useState([]);
  const [expandedTreeKeys, setExpandedTreeKeys] = useState([]);

  //初始化数据
  useEffect(() => {
    const initData = async (value) => {
      //菜单
      var res = initialState?.currentUser?.menuList;
      if (res) {
        SetTreeData(res);
      }
      //选中菜单
      setCheckedTreeKeys(props.roleMenus);
      setExpandedTreeKeys(props.roleMenus);
      await actionclasslist().then((re) => {
        if (re.isSuccess) {
          SetActionClassData(re.data);
        }
      });
    };
    initData();
  }, []);

  const onSelect = (keys, info) => {
    SetCurrentMenu(info.node.info);
  };

  //获取Actionlist
  const getActionlist = async (value) => {
    await actionlist(value).then((re) => {
      if (re.isSuccess) {
        var list = [];
        re?.data.map((item) => {
          list.push({ label: item.name, value: item.id });
        });
        SetActionData(list);
        var cl = new Set(checkedList);
        // 交集
        setCheckedList(list.map((x) => x.value).filter((x) => cl.has(x)));
      }
    });
  };
  const onCheckAllChange = (e) => {
    setCheckedList(e.target.checked ? actionData?.map((item) => item.value) : []);
    setIndeterminate(false);
    setCheckAll(e.target.checked);
  };
  const onCheckChange = (list) => {
    setCheckedList(list);
    setIndeterminate(!!list.length && list.length < actionData.length);
    setCheckAll(list.length === actionData.length);
  };

  //选中树的复选框
  const onCheckTree = (value, info) => {
    //父节点下有数据不允取消父节点
    const result = info.checkedNodes.find((item) => {
      return item.parentId === info.node.key;
    });
    if (result) {
      return;
    }
    //选中子节点父节点也跟着选中，选中父节点子节点没有变化
    var list =
      info.node.parentId != 0
        ? [...new Set([...[info.node.parentId], ...value.checked])]
        : value.checked;
    setCheckedTreeKeys(list);
    setExpandedTreeKeys(list);
  };

  //展開關閉樹
  const onExpandTree = (expandedKeysValue) => {
    setExpandedTreeKeys(expandedKeysValue);
  };

  //
  const loopMenuItem = (menus) =>
    menus?.map((item, index) => {
      return {
        parentId: item.parentId,
        key: item.id,
        title: item.name,
        value: item.id,
        routes: item.routes && loopMenuItem(item.routes),
        children: item.routes && loopMenuItem(item.routes),
      };
    });

  return (
    <ModalForm
      title="授权菜单"
      layout={'horizontal'}
      visible={props.modalVisit}
      onVisibleChange={props.setModalVisit}
      initialValues={{
        state: true,
      }}
      onFinish={async (values) => {
        var data = await editRoleMenu({
          tenantId: props.currentRow.id,
          menuIds: checkedTreeKeys,
        });
        data.isSuccess ? message.success(data.msg) : message.error(data.msg);
        return data.isSuccess;
      }}
    >
      <Row gutter={16}>
        <Col span={18} push={6}>
          <Card>
            <ProFormSelect
              fieldProps={{
                mode: 'multiple',
              }}
              label="后台模块"
              name="actionClassList"
              placeholder="后台模块"
              value={actionClassList}
              onChange={async (values) => {
                await getActionlist(values);
              }}
              request={() => {
                var list = [];
                [...new Set(actionClassData)]?.map((item, index) => {
                  list.push({ label: item, value: item });
                });
                return list;
              }}
            />

            <br />
            <ProForm.Item name="checkedList" label="功能项">
              {/* <Checkbox indeterminate={indeterminate} onChange={onCheckAllChange} hecked={checkAll}>
                全选
              </Checkbox>
              <br /> */}
              <Checkbox.Group options={actionData} value={checkedList} onChange={onCheckChange} />
            </ProForm.Item>
          </Card>
        </Col>
        <Col span={6} pull={18}>
          <Tree
            checkable
            showIcon
            height={600}
            checkStrictly={true}
            onSelect={onSelect}
            onCheck={onCheckTree}
            checkedKeys={checkedTreeKeys}
            expandedKeys={expandedTreeKeys}
            onExpand={onExpandTree}
            treeData={loopMenuItem(treeData)}
            key="id"
          />
        </Col>
      </Row>
    </ModalForm>
  );
};

export default EditMentModalForm;
